Page({
  data: {
    companyName: '',
    creditCode: '',
    licenseFiles: [],
    legalPerson: '',
    legalPersonId: '',
    idCardFiles: []
  },

  onCompanyNameChange(e) {
    this.setData({
      companyName: e.detail.value
    });
  },

  onCreditCodeChange(e) {
    this.setData({
      creditCode: e.detail.value
    });
  },

  onLicenseChange(e) {
    this.setData({
      licenseFiles: e.detail.files
    });
  },

  onLegalPersonChange(e) {
    this.setData({
      legalPerson: e.detail.value
    });
  },

  onLegalPersonIdChange(e) {
    this.setData({
      legalPersonId: e.detail.value
    });
  },

  onIdCardChange(e) {
    this.setData({
      idCardFiles: e.detail.files
    });
  },

  submit() {
    const {
      companyName,
      creditCode,
      licenseFiles,
      legalPerson,
      legalPersonId,
      idCardFiles
    } = this.data;

    if (!companyName || !creditCode || !licenseFiles.length || !legalPerson || !legalPersonId || !idCardFiles.length) {
      wx.showToast({
        title: '请填写完整信息',
        icon: 'none'
      });
      return;
    }

    // 上传文件
    const uploadTasks = [
      ...licenseFiles.map(file => this.uploadFile(file.url, 'license')),
      ...idCardFiles.map(file => this.uploadFile(file.url, 'idCard'))
    ];

    Promise.all(uploadTasks)
      .then(fileUrls => {
        const [licenseUrl, ...idCardUrls] = fileUrls;
        return this.submitCertification({
          companyName,
          creditCode,
          licenseUrl,
          legalPerson,
          legalPersonId,
          idCardUrls
        });
      })
      .then(() => {
        wx.showToast({
          title: '提交成功',
          icon: 'success'
        });
        setTimeout(() => {
          wx.navigateBack();
        }, 1500);
      })
      .catch(err => {
        wx.showToast({
          title: err.message || '提交失败',
          icon: 'none'
        });
      });
  },

  uploadFile(filePath, type) {
    return new Promise((resolve, reject) => {
      wx.uploadFile({
        url: 'https://api.example.com/upload',
        filePath,
        name: 'file',
        formData: { type },
        success: (res) => {
          if (res.statusCode === 200) {
            resolve(JSON.parse(res.data).url);
          } else {
            reject(new Error('上传失败'));
          }
        },
        fail: () => {
          reject(new Error('网络错误'));
        }
      });
    });
  },

  submitCertification(data) {
    return new Promise((resolve, reject) => {
      wx.request({
        url: 'https://api.example.com/certification',
        method: 'POST',
        data,
        success: (res) => {
          if (res.statusCode === 200) {
            resolve();
          } else {
            reject(new Error('提交失败'));
          }
        },
        fail: () => {
          reject(new Error('网络错误'));
        }
      });
    });
  },

  goBack() {
    wx.navigateBack();
  }
}); 